package com.finger.hospservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finger.commonutil.exception.YyghException;
import com.finger.hospservice.listener.ExcelDictListener;
import com.finger.hospservice.listener.ExcelStudentListener;
import com.finger.hospservice.mapper.DictMapper;
import com.finger.hospservice.service.DictService;
import com.finger.modelservice.model.cmn.Dict;
import com.finger.modelservice.vo.cmn.DictEeVo;
import com.finger.modelservice.vo.student.FinalStu;
import com.finger.modelservice.vo.student.SevenClass;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findDict(Long id) {

        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();

        dictQueryWrapper.eq("parent_id",id);

        List<Dict> dicts = baseMapper.selectList(dictQueryWrapper);

        for (Dict dict : dicts) {

            Long dictId = dict.getId();

            // 设置下边是否还有层级
            dict.setHasChildren(this.hasChildren(dictId));

        }
        return dicts;
    }

    @Override
    public void downLoadDict(HttpServletResponse response) {
        try{

            // 设置响应体要下载excel表格
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

            List<Dict> dicts = baseMapper.selectList(null);

            List<DictEeVo> dictEeVos = new ArrayList<>(dicts.size());

            for (Dict dict : dicts) {

                DictEeVo dictEeVo = new DictEeVo();

                dictEeVos.add(dictEeVo);

                BeanUtils.copyProperties(dict,dictEeVo);

            }
//            ArrayList<SevenClass> sevenClasses = new ArrayList<>();
//
//            EasyExcel.read("X:\\vscode\\在校生学籍.xlsx",SevenClass.class,new ExcelStudentListener(sevenClasses)).sheet().doRead();
//
//            ArrayList<FinalStu> stus = new ArrayList<>();
//            Integer i = 1;
//            for (SevenClass sevenClass : sevenClasses) {
//
//
//                if(sevenClass.getClassName() .equals("初中2020级1班")){
//
//                    FinalStu finalStu = new FinalStu();
//                    BeanUtils.copyProperties(sevenClass,finalStu);
//                    finalStu.setClassName("八一班");
//                    finalStu.setIndex(i++);
//                    finalStu.setIsJoin("是");
//                    finalStu.setStandard("60");
//                    stus.add(finalStu);
//
//                }
//            }

//            try {
//                FileOutputStream fileOutputStream = new FileOutputStream(new File("X:\\八一班"));
//                EasyExcel.write(fileOutputStream,FinalStu.class).sheet("八一班").doWrite(stus);
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }


            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("数据字典")
                    .doWrite(dictEeVos);

        }catch (Exception e){
            throw new YyghException("文件下载失败",201);
        }
    }

    @Override
    // 方法执行后清除所有缓存
    @CacheEvict(value = "dict",allEntries = true)
    public void uploadDict(MultipartFile file) {

        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new ExcelDictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new YyghException("文件上传失败",201);
        }
    }

    // 判断是否有子节点
    public boolean hasChildren(Long id){

        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();

        dictQueryWrapper.eq("parent_id",id);

        Integer count = baseMapper.selectCount(dictQueryWrapper);

        return count>0;
    }

    // 根据字典代码和值查找名字
    public String getName(String dictCode,String value){

        if(dictCode.isEmpty()){
            QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
            dictQueryWrapper.eq("value",value).select("name");
            Dict dict = baseMapper.selectOne(dictQueryWrapper);
            return dict.getName();
        }else{
            QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
            dictQueryWrapper.eq("dict_code",dictCode).select("id");

            Dict dict = baseMapper.selectOne(dictQueryWrapper);

            Dict finalDict = baseMapper.selectOne(new QueryWrapper<Dict>().select("name").eq("parent_id", dict.getId()).eq("value", value));

            return finalDict.getName();
        }
    }

    @Override
    public List<Dict> findDictByCode(String code) {

//        return baseMapper.selectList(new QueryWrapper<Dict>()
//                .eq("parent_id",baseMapper.selectOne(new QueryWrapper<Dict>()
//                        .eq("dict_code",code).select("id")).getId())
//                .select("name","id").orderByAsc("name"));
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("dict_code",code).select("id");
        Dict dict = baseMapper.selectOne(dictQueryWrapper);

        List<Dict> list = baseMapper.selectList(new QueryWrapper<Dict>().eq("parent_id", dict.getId()));

        return list;

    }
}
